package sg.edu.nus.comp.icreate.ivletalk.events;

import java.util.ArrayList;
import java.util.List;

import sg.edu.nus.comp.icreate.ivletalk.EventBaseActivity;
import sg.edu.nus.comp.icreate.ivletalk.R;
import sg.edu.nus.comp.icreate.ivletalk.User;
import sg.edu.nus.comp.icreate.ivletalk.module.MainActivity;
import sg.edu.nus.comp.icreate.ivletalk.utils.net.DataPuller;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;

public class DisplayEvents extends EventBaseActivity {
	public static final String LOGIN_INTENT = "getback";
	public static List<Event> events = new ArrayList<Event>();
	public static final String EXTRA_NAME_EVENT_POSITION = "sg.edu.nus.comp.icreate.ivletalk.extra.eventPosition";

	private ListView eventList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_display_events);
		eventList = (ListView) findViewById(R.id.eventList);
		try {
			getEvents();
		} catch (Exception e) {
			Log.e("error", "Error in getEvents", e);
		}

		ArrayAdapter<Event> adapter = new ArrayAdapter<Event>(this, android.R.layout.simple_list_item_1, events);
		eventList.setAdapter(adapter);
		eventList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				((DisplayEvents) parent.getContext()).goToItem(position);
			}
		});
	}

	@SuppressWarnings("unchecked")
	private void getEvents() throws Exception {

		String url = "https://ivle.nus.edu.sg/api/Lapi.svc/StudentEvents?APIKey=" + MainActivity.APIKEY + "&AuthToken=" + User.getInstance().getToken()
				+ "&TitleOnly=false&Output=XML";
		DataPuller eventsListPuller = new DataPuller(new EventsXmlParser());
		eventsListPuller.execute(url);
		events = (List<Event>) eventsListPuller.get();

	}

	@Override
	public void goToItem(int position) {
		Intent intent = new Intent(this, ListEventElementActivity.class);
		intent.putExtra(EXTRA_NAME_EVENT_POSITION, position);
		startActivity(intent);
	}

	@Override
	public Boolean goNewPost() {
		Intent intent = new Intent(this, NewEventActivity.class);
		startActivity(intent);
		return true;

	}

	public List<Event> getDisplayedItemList() {
		return events;
	}

	@Override
	protected boolean handleActionRefresh() {
		try {
			getEvents();
			((BaseAdapter) eventList.getAdapter()).notifyDataSetChanged();
		} catch (Exception e) {
			Log.e("error", "Error in handleActionRefresh", e);
		}
		return true;
	}

}
